import { checkToken, getToken, showLoading } from './utils/util'
import { fetch } from './services/user'

//app.js
App({
  state: {
    userInfo: {},
    checklists: [],
    cid: "0"  // current checked checklist id
  },

  onLaunch: function () {
    if(!checkToken()) {
      wx.reLaunch({
        url: './pages/welcome/index'
      })
    } else if (!this.state.userInfo.id) {
      const _this = this
      fetch().then((data) => {
        _this.state.userInfo = data

        if (_this.fetchChecklistsCallback) {
          _this.fetchChecklistsCallback(data.id)
        }
      })
    }
  },

  /**
   * 获取当前待办清单的ID
   */
  getCurrentChecklistId: function () {
    return this.state.cid === '0'
         ? this.state.checklists.find((u) => u.isStatic).id
         : this.state.cid
  },
  /**
   * 更新指定task的某个字段
   */
  updateSpecifiedTaskField: function (listId, index, field, value) {
    const task = this.state.checklists
                 .find((u) => u.id === listId).tasks
                 .find((v) => v.index === index)
    task[field] = value
  },
  /**
   * 删除指定的task
   */
  deleteSpecifiedTask: function (listId, index) {
    const tasks = this.state.checklists.find((u) => u.id === listId).tasks
    const _index = tasks.findIndex((u) => u.index === index)
    tasks.splice(_index, 1)
    tasks.map((item) => {
      if (item.index > index) {
        item.index--
      }
    })
  },
  /**
   * 添加新的清单
   */
  addNewChecklist: function (checklist) {
    this.state.checklists.push(checklist)
  },
  /**
   * 删除清单
   */
  deleteChecklist: function (listId) {
    const _index = this.state.checklists.findIndex((u) => u.id === listId)
    this.state.checklists.splice(_index, 1)
  }
})